package com.github.wujichen158.andemusic.eventsetting;

import com.github.wujichen158.andemusic.AndeMusic;
import com.github.wujichen158.andemusic.lib.Reference;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.registries.IForgeRegistry;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.Map;

public class MusicRegister {
    private static final Map<String, SoundEvent> SOUND_EVENTS = Maps.newHashMap();

    public MusicRegister() {
        registerSounds();
    }

    private void registerSounds() {
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, Object>>() {}.getType();

        String resourcePath = String.format("/assets/%s/sounds.json", Reference.MOD_ID);
        try (InputStream inputStream = getClass().getResourceAsStream(resourcePath)) {
            if (inputStream == null) {
                throw new IOException("Sound resource not found: " + resourcePath);
            }

            try (InputStreamReader reader = new InputStreamReader(inputStream)) {
                Map<String, Object> soundsJson = gson.fromJson(reader, type);

                soundsJson.forEach((soundName, soundObj) -> SOUND_EVENTS.put(soundName, register(soundName)));
            }
        } catch (IOException e) {
            AndeMusic.LOGGER.error("Failed to load sounds.json: ", e);
        }
    }

    @SubscribeEvent
    public void registerSounds(RegistryEvent.Register<SoundEvent> event) {
        IForgeRegistry<SoundEvent> registry = event.getRegistry();
        for (SoundEvent soundEvent : SOUND_EVENTS.values()) {
            registry.register(soundEvent);
        }
    }

    public static SoundEvent getSound(String name) {
        return SOUND_EVENTS.get(name);
    }

    private SoundEvent register(String musicName) {
        ResourceLocation rl = new ResourceLocation(Reference.MOD_ID, musicName);
        return new SoundEvent(rl).setRegistryName(rl);
    }
}